#include "head.h"
int pipe_fd[2];
void signalHandle(int num){
    printf("触发2号信号函数，准备退出程序\n");
    write(pipe_fd[1],"1",1);
}
int main(int argc,char *argv[]){
    //初始化管道
    pipe(pipe_fd);
    //注册信号

    if(fork() != 0){
        signal(2,signalHandle);
        wait(NULL);
        printf("父进程退出\n");
        exit(0);
    }
    setpgid(0,0);
    // 读取配置文件
    Config my_config = load_config();

    //初始化线程
    status_t status;
    initPthreads(&status,4);

    //初始化socket_fd
    int socket_fd;
    initSocketfd(&socket_fd,my_config.ip, my_config.port);
    //printf("socket_fd: %d \n",socket_fd);

    int epoll_fd;
    initEpollfd(&epoll_fd);
    //printf("epollfd : %d \n",epoll_fd);

    epoll_add(epoll_fd,socket_fd);

    //添加对管道的监听
    epoll_add(epoll_fd,pipe_fd[0]);
    while(1){
        struct epoll_event events[1024];
        int epoll_num = epoll_wait(epoll_fd,events,1024,-1);

        for(int i = 0 ; i < epoll_num ; i++){
            int cfd = events[i].data.fd;
            if(cfd == socket_fd){
                printf("有新连接\n");
                int net_fd = accept(socket_fd,NULL,NULL);
                pthread_mutex_lock(&status.lock);
                enqueue(&status.q,net_fd);
                pthread_cond_broadcast(&status.cond);
                pthread_mutex_unlock(&status.lock);
            }else if(cfd == pipe_fd[0]){
                char buf[5] = {0};
                read(pipe_fd[0],buf,sizeof(buf));

                pthread_mutex_lock(&status.lock);
                status.end_flag = 1;
                pthread_cond_broadcast(&status.cond);
                pthread_mutex_unlock(&status.lock);

                for(int j = 0 ; j < 4 ; j++){
                    pthread_join(status.pthreads[j],NULL);
                }
                printf("子进程退出\n");
                pthread_exit(NULL);
            }
        }
    }
    close(socket_fd);
    close(epoll_fd);
    return 0;
}

